<template>
  <el-main>
    <el-row class="bg">
      <el-col class="hidden-md-and-down" v-if="fieldParentPicList.length>0" :span="fieldParentPicList.length>=3 ? 14:13" :offset="1">
          <el-carousel
            :interval="5000"
            height="300px"
            :type="fieldParentPicList.length>=3 ? 'card':''"
            :arrow="fieldParentPicList.length==1 ? 'never':'hover'"
            :indicator-position="fieldParentPicList.length==1 ? 'none':'outside'"
            :autoplay="fieldParentPicList.length>1"
          >
            <el-carousel-item v-for="(pic,index) in fieldParentPicList" :key="index">
                <div class="fieldPic" :style=" 'background-image:url('+pic+');' "></div>
            </el-carousel-item>
          </el-carousel>
      </el-col>
      <el-col class="fieldRemark" :lg="8" :md="23" :xs="23">
        <el-row>
          <el-col class="fieldTitle">{{fieldParentList.name}}</el-col>
          <el-col></el-col>
        </el-row>
        <el-row v-if="fieldParentList.locate">
          <i class="el-icon-location"/>位置：<span>{{fieldParentList.locate}}</span>
        </el-row>
        <el-row v-if="fieldParentList.username">
          <i class="el-icon-user-solid" />负责人：<span>{{fieldParentList.username}}</span>
        </el-row>
        <el-row v-if="fieldParentList.phone">
          <i class="el-icon-phone" />联系电话：<span>{{fieldParentList.phone}}</span>
        </el-row>
        <el-row v-if="fieldParentList.remark">
          <i class="el-icon-star-on" />场馆简介：
          <div class="remark" :style="showremark? 'height: 22px;':''">
            {{fieldParentList.remark}}
            <div v-if="fieldParentList.remark.length>28" class="show" @click="showremark=!showremark">
              {{showremark ? '展开':'收起' }}
            </div>
          </div>
        </el-row>

      </el-col>
    </el-row>
    <el-row style="margin:30px">
      <el-col :lg="showBookList(bookList) ? 14 : 24" :md="24" :xs="24" style="margin-bottom:30px">
        <el-tabs v-model="bookDate" @tab-click="handleTabClick" >
          <el-tab-pane
            :lazy="true"
            :disabled="parentWeekList.indexOf(item.todayWeek)==-1"
            v-for="(item,index) in canBookDate"
            :key="index"
            :label="item.paneName"
            :name="`${index}`"
          >
            <el-table height="75vh" :data="parentTimeList">
              <el-table-column prop="time" label="时间段 / 场馆名称" width="130" align="center"></el-table-column>
              <el-table-column :label="t.status==2 ? t.name+'（维护中）':t.name+'(¥'+t.cost+')'" v-for="t in showAllFieldList" :key="t.id" align="center">
                <template slot-scope="scope">
                  <el-tooltip v-if="reFlash" :open-delay="500" :disabled="!showTip(t,scope.row.id)" effect="dark" placement="right">
                    <div slot="content">
                      可预约人数：{{t.seat}}
                      <br/>
                      已预约人数：{{t.seat-t.book[scope.row.id].leftseat}}
                      <br/>
                      时段价格：¥&nbsp;{{t.cost}}
                    </div>
                    <el-button
                      v-if="reFlash&&t.book[scope.row.id]!=null"
                      size="mini"
                      :type="showType(t,scope.row.id)"
                      :disabled="t.status==2 || canClickDanger(t,scope.row.id) || obsolete(scope.row.time,t,scope.row.id) ||hasBook(t.id,scope.row.id)"
                      @click="readyBookField(t.book[scope.row.id],t)"
                    >{{showText(t,scope.row.id)}}</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>

      <el-col v-if="showBookList(bookList)" :lg="{span:9,offset:1}" :md="24" :xs="24">
        <el-card>
          <div slot="header">
            <span>已选场馆</span>
          </div>
          <el-form label-position="top">
            <div v-for="(n,index) in bookList" :key="index">
              <el-form-item v-if="n"  :label="n.date">
                <div
                  class="bookItem"
                  :key="i"
                  v-for="(tag,i) in bookList[index].list"
                  :disable-transitions="true"
                  :style="tag.remark=='' ? '':'border: 1px solid #E6A23C;'"
                >
                <span class="bookText"><b>¥{{tag.bookCost}}</b>&nbsp;{{showBookItem(tag)}}</span>
                  <el-popover
                    placement="bottom-start"
                    title="预约备注"
                    width="300"
                    trigger="click"
                    @show="showRemark(tag.remark)"
                    @hide="saveRemark(tag,bookRemark)"
                  >
                    <el-input size="mini" v-model="bookRemark" :maxlength="15" show-word-limit clearable></el-input>
                    <i v-if="tag.remark==''" class="el-icon-edit-outline" slot="reference">添加备注</i>
                    <i v-else class="el-icon-edit-outline" slot="reference">修改备注</i>
                  </el-popover>
                  <i class="el-icon-circle-close" @click="deleteBookList(tag.fid,tag.tid,index,tag.bookCost)">取消选择</i>
                </div>

              </el-form-item>
            </div>
            <el-row type="flex" justify="space-between" align="middle">
              <el-col :span="6" class="countCost">
                <span style="font-size:12px;color:#909399;">预计:</span>
                <count-to
                  :start-val="countCost"
                  :end-val="countCost"
                  :decimals="2"
                  separator=","
                  prefix="¥ "
                />
              </el-col>
              <el-col :span="4"><el-button type="primary" @click="confirmBook">确认预约</el-button></el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>

    </el-row>
    <my-dialog
      :title="ordersDialog.title"
      :width="ordersDialog.width"
      :height="ordersDialog.height"
      :visible="ordersDialog.visible"
      @onClose="onOrdersClose"
      @onConfirm="onOrdersConfirm"
    >
      <div slot="content">
        <el-alert show-icon :title="ordersAlertTitle" :type="ordersAlertType" :closable="false" />
        <el-table
          :data="ordersTableData"
          :summary-method="getSummaries"
          show-summary
        >
        <el-table-column type="index" align="center" width="70"></el-table-column>
        <el-table-column label="预约场馆">
          <template  slot-scope="scope">
            {{showFieldName(scope.row.fid)}}
          </template>
        </el-table-column>
        <el-table-column label="预约时间">
          <template  slot-scope="scope">
            {{showBookDateTime(scope.row.tid,scope.row.bookStartDate)}}
          </template>
        </el-table-column>
        <el-table-column prop="bookCost" align="right" label="价格">
          <template  slot-scope="scope">
            {{scope.row.bookCost | showCost}}
          </template>
        </el-table-column>
        </el-table>
        <div v-if="allPoint>0&&allCost>0||point>0" style="text-align:right;margin-top:20px">
          <el-popover
            placement="left"
            width="100"
            trigger="click"
          >
            <el-input-number v-model="point" :step="100" size="mini" :min="0" :max="canUsePoint"></el-input-number>
            <el-link v-if="point==0||point==null" slot="reference" type="warning">可使用{{canUsePoint}}积分抵扣{{canUsePoint/1000}}元</el-link>
            <el-link v-if="point>0&&point!=null" slot="reference" type="success">使用{{point}}积分抵扣{{point/1000}}元</el-link>
          </el-popover>
        </div>

      </div>
    </my-dialog>
    <my-dialog
      ref="payDialogRef"
      :title="payDialog.title"
      :width="payDialog.width"
      :height="payDialog.height"
      :visible="payDialog.visible"
      @onClose="onPayClose"
      @onConfirm="onPayConfirm"
    >
      <div slot="content">
        <el-result v-if="balance<allCost" icon="warning" title="余额不足">
          <template slot="extra">
            <router-link :to="'/account/accountSafe'">
              <el-link type="primary">前往充值</el-link>
            </router-link>
          </template>
        </el-result>
        <div v-else>
          <h1 style="color:red;text-align:center;">¥ {{allCost.toFixed(2)}}</h1>
          <el-statistic
            class="tiptext"
            ref="statistic"
            format="m:ss"
            prefix="下单成功! 请在"
            suffix="时间内完成订单支付"
            :value="ordersStopCountDown"
            time-indices
          />
          <my-valid-input :type="true" @giveInputValue="getPayInputValue" ref="payInputRef"></my-valid-input>
          <el-row v-if="payCount>=3" style="margin-top:20px">
            <el-col :span="7" :offset="6">
              <el-input v-model="payCode" placeholder="输入正确结果" clearable />
            </el-col>
            <el-col :span="5" :offset="1">
              <el-image :src="codeImage" @click="getMathCodeImage" class="codeImg"></el-image>
            </el-col>
          </el-row>
        </div>
      </div>
    </my-dialog>

  </el-main>
</template>

<script>
import setViewTitle  from '@/utils/setTitle'
import myValidInput from '@/components/MyValidInput';
import countTo from 'vue-count-to';
import myDialog from "@/components/MyDialog/index";
import { getValidFieldListApi } from "@/api/field";
import { getTimesApi } from "@/api/times";
import { getPicturesByBidApi } from "@/api/pictures";
import { addNewOrdersApi,finishPayApi } from "@/api/orders";
import { getAssetByUid, checkAssetKeyApi } from "@/api/asset"
import { getMathCodeImageApi, checkMathCodeApi} from "@/api/captcha";
import { getFieldBookApi, addBookFieldApi, deleteFieldBookApi,getAllFieldBookApi } from "@/api/fieldBook";
  export default {
    components: { countTo,myDialog,myValidInput },
    data(){
      return{
        //已预约
        booklist:[],
        //星期
        weeks: ['周日','周一','周二','周三','周四','周五','周六'],
        //展开父级场馆简介
        showremark:false,
        //父级id
        pid: "",
        //父子的所有id
        allIds:[],
        //所有符合条件的场馆
        fieldAllList: [],
        //用于展示的所有场馆
        showAllFieldList:[],
        //符合条件的父级场馆
        fieldParentList:"",
        //所有符合条件的子级场馆
        fieldSonList:[],
        //父级场馆所有图片
        fieldParentPicList:[],
        //选中的预约日期栏
        bookDate:"",
        //可选择的日期栏
        canBookDate: [],
        //所有时间段
        timeList:[],
        //父级时间段
        parentTimeList: [],
        //父级开放星期
        parentWeekList:[],
        //预约情况数据
        fieldBookData:[],
        //预约数据
        bookList:[],
        //预约备注
        bookRemark: "",
        //强制刷新
        reFlash: true,

        //预约前花费
        countCost: 0,
        //预约后花费
        allCost: 0,
        //是否全部预约提示
        ordersAlertTitle: "",
        //是否全部预约提示类型
        ordersAlertType: "",
        //资产id
        assetId: "",
        //用户金额
        balance: 0,
        //用户所有积分
        allPoint: 0,
        //用户此次订单可用积分
        canUsePoint:0,
        //将使用积分
        point: 0,
        //确认订单弹框
        ordersDialog:{
          title: "确认订单",
          width: 660,
          height: 300,
          visible: false,
        },
        //预约订单项
        ordersTableData:[],
        //已完成或取消预约的订单ID集
        ordersBookIds: [],
        //完成建立订单后的返回
        newOrders:'',
        //支付弹框
        payDialog: {
          title: "支付订单",
          width: 500,
          height: 120,
          visible: false,
        },
        //订单倒计时
        ordersStopCountDown: 0,
        //支付密码输入框
        payInput: "",
        //错误支付次数
        payCount: 0,
        //验证码
        codeImage:"",
        //验证码输入
        payCode:"",
      };
    },
    created(){
      //获取路由信息
      this.pid = this.$route.params.pid;
      //加入父级的id作为查找参数
      this.allIds.unshift(this.pid);
      if(this.pid!=null){
        this.getValidFieldList();
        setViewTitle(Object.assign({}, this.$route),this.$route.params.name)
      }
    },
    methods:{
      //获取个人预约情况
      async getMyBook(){
        let parm = {
          uid:this.$store.getters.userId,
          startTime:this.canBookDate[this.bookDate].dateTime + ' 0:00:00',
          endTime:this.canBookDate[this.bookDate].dateTime + ' 23:59:59',
        };
        let res = await getAllFieldBookApi(parm);
        if(res&&res.code==200){
          if(res.data.list.length>0){
            this.booklist = [];
            res.data.list.filter(item=>{
              if(item.status==0||item.status==1||item.status==2){
                const { fid,tid,startTime } = item;
                let sdate = startTime.split(" ")[0];
                this.booklist.push({ fid,tid,sdate });
              }
            });
          }
        }
      },

      //点击Tab获取
      handleTabClick(tab){
        if(this.bookDate===tab.name){
          this.getMyBook();
          this.getFieldBook();
        }

      },
      //搜索父子级场馆
      async getValidFieldList(){
        let res = await getValidFieldListApi({pid:this.pid});
        if(res&&res.code==200){
          this.fieldAllList = res.data;
          //获取父级
          this.fieldAllList.some(item=>{
            if(item.id==this.pid){
              this.fieldParentList = item;
              //格式化时间段
              this.fieldParentList.times = this.fieldParentList.times.split(",").map(Number);
              //获取格式化后的开放星期
              this.parentWeekList = this.fieldParentList.week.split(",").map(Number);
              return true;
            }
          });
          //获取所有子级
          let coypSonList = this.fieldAllList.filter(item=>{
            //加入子级id作为查找参数
            this.allIds.push(item.id);
            return item.pid==this.pid
          });
          //格式化时间段
          coypSonList.filter(item=>{  item.times= item.times.split(",").map(Number); })
          this.fieldSonList = coypSonList;
          //父级若有有封面，表示有图片可以渲染轮播图
          if(this.fieldParentList.url!=null){
            this.getPicturesByBidApi(this.fieldParentList.fieldNo);
          }
          this.getTimes();
        }
      },
      //获取父级场馆图片
      async getPicturesByBidApi(bid){
        let res = await getPicturesByBidApi({"bid":bid})
        if(res&&res.code==200){
          res.data.forEach(item => { this.fieldParentPicList.push(item.url) });
        }
      },
      //预约日期
      getBookdate(addDayCount){
        let day = new Date();
        day.setDate(day.getDate()+addDayCount);//获取AddDayCount天后的日期
        let y = day.getFullYear();
        let m = day.getMonth()+1;//获取当前月份的日期
        let d = day.getDate();
        let w = day.getDay();
        return {
          //显示tab名
          paneName : m+"-"+d+"-"+this.weeks[w],
          //用于禁用
          todayWeek: w,
          //预约的年月日，作为查找参数
          dateTime: y+"-"+m+"-"+d
        }
      },
      //获取自定义的所有时间段
      async getTimes() {
        let res = await getTimesApi();
        if(res && res.code == 200) {
          this.timeList = res.data;
          this.getParentTimes();
        }
      },
      //从所有时间段中挑选出父级的时间段数据
      getParentTimes(){
        this.timeList.forEach(item=>{
          this.fieldParentList.times.forEach(index=>{
            if(item.id == index){
              this.parentTimeList.push(item);
            }
          })
        })
        this.inPageTab();
      },
      //执行渲染可选择日期 并 指定进入预约页面默认选中的日期
      inPageTab(){
        let maxday = 3;
        //此处根据权限可确定最多提前预约几天
        if(this.hasPerm('field:fieldBook:early')){ maxday = 7 ;}
        for(let i = 0;i<maxday;i++){
          //渲染可选择日期
          this.canBookDate.push(this.getBookdate(i))
        }
        this.canBookDate.some((item,index)=>{
          if(this.parentWeekList.indexOf(item.todayWeek)!=-1){
            //指定进入预约页面默认选中的日期，避免默认选择不开放的日期栏
            this.bookDate = index.toString();
            return true;
          };
        })
        //查找已预约
        this.getMyBook();
        this.getFieldBook();
      },
      //获取预约情况
      async getFieldBook(){
        let param ={
          fids:this.allIds.toString(),
          date:this.canBookDate[this.bookDate].dateTime
        }
        let res = await getFieldBookApi(param);
        if(res&&res.code==200){
          let copylist = res.data;
          this.showAllFieldList = [];
          if(this.hasPerm('field:fieldBook:all')||this.fieldAllList.length==1){
            this.showAllFieldList = this.fieldAllList
          }else{
            this.showAllFieldList = this.fieldSonList
          }
          this.showAllFieldList.map(item=>{
            //因为tid没有0，添加一个下标为0的数据 或是 注意获取时下标减1
            item.book=[{tid:0}]
            //任何场馆添加属性
            this.parentTimeList.forEach(element=>{
              item.book[element.id] = {tid:element.id,leftseat:item.seat,onclick:false}
              //回显已选择
              if(this.bookList[this.bookDate]!=undefined){
                this.bookList[this.bookDate].list.forEach(val=>{
                  if(val.fid==item.id&&val.tid==element.id){
                    this.$set(item.book[element.id],'onclick',true);
                  }
                })
              }
            })
            //记录已预约情况
            copylist.forEach(index=>{
              if(item.id==index.fid){
                item.book.forEach(val=>{
                  if(val.tid == index.tid){
                    val.leftseat -=index.haveBookNum
                  }
                })
              }
            })
          })
        }
      },
      //按钮显示内容
      showText(fieldItem,tid){
        if(fieldItem.times.indexOf(tid)==-1){
          return "闭"
        }else if(fieldItem.book[tid].onclick){
          return "✔"
        }else if(
          fieldItem.book[tid].leftseat==0 ||
          this.showAllFieldList[0].book[tid].leftseat<this.showAllFieldList[0].seat&&fieldItem.pid!=0
        ){
          return "满"
        }else{
          return fieldItem.book[tid].leftseat
        }
      },
      //是否开启提示
      showTip(fieldItem,tid){
        if(fieldItem.times.indexOf(tid)==-1){
          return false;
        }else if(fieldItem.book[tid].onclick){
          return false;
        }else if(
          fieldItem.book[tid].leftseat==0 ||
          this.showAllFieldList[0].book[tid].leftseat<this.showAllFieldList[0].seat&&fieldItem.pid!=0
        ){
          return false;
        }else{
          return true;
        }
      },
      //按钮样式
      showType(fieldItem,tid){
        if(fieldItem.times.indexOf(tid)==-1){
          return "info"
        }else if(fieldItem.book[tid].onclick){
          return "success"
        }else if(
          fieldItem.book[tid].leftseat==0 ||
          this.showAllFieldList[0].book[tid].leftseat<this.showAllFieldList[0].seat&&fieldItem.pid!=0
        ){
          return "danger"
        }else{
          return ""
        }
      },
      //点击相应的逻辑(重要)
      readyBookField(b,f){
        if(f.times.indexOf(b.tid)==-1){
          this.$message.info("抱歉！该时间段"+f.name+"还未对外开放，请选择其它时间！")
          return;
        }
        if(
          b.leftseat==0 ||
          this.showAllFieldList[0].book[b.tid].leftseat<this.showAllFieldList[0].seat&&f.pid!=0
        ){
          this.$message.info("抱歉！当天该时间段的"+f.name+"预约名额已满，请选择其它时间！")
          return;
        }
        this.checkHaveBook(b,f.id)
        if(b.leftseat!=0&&!b.onclick || b.leftseat>=0&&b.onclick){
          this.reFlash = false;
          b.onclick = !b.onclick;
          if(b.onclick){
            if(this.bookList[this.bookDate]===undefined){
              this.bookList[this.bookDate] = [];
              this.bookList[this.bookDate].date = this.canBookDate[this.bookDate].paneName;
              this.bookList[this.bookDate].dateTime = this.canBookDate[this.bookDate].dateTime;
              this.bookList[this.bookDate].list = [];
            }
            this.bookList[this.bookDate].list.push({fid:f.id,tid:b.tid,bookCost:f.cost,remark:'',date:this.canBookDate[this.bookDate].dateTime});
            this.countCost += f.cost;
          }else{
            this.deleteBookList(f.id,b.tid,this.bookDate,f.cost)
          }
          this.$nextTick(()=>{
            this.reFlash = true
          })
        }
        this.$forceUpdate();
      },
      //点击同时间段按钮的变化
      checkHaveBook(p,fid){
        this.showAllFieldList.forEach(item=>{
          item.book.some(list=>{
            //切换同时间段按钮
            if(list.tid==p.tid&&list.onclick&&item.id!=fid){
              list.onclick = false;
              this.deleteBookList(item.id,list.tid,this.bookDate,item.cost)
              return true;
            }
          })
        })
      },
      //去除预约选择并关联表格变化(重要)
      deleteBookList(fid,tid,index,cost){
        //改变表格
        //只有当处于同一日期栏才会关联改变表格，否则只改变右侧信息栏
        if(this.bookDate==index)
          this.reFlash = false;
          this.showAllFieldList.map(item=>{
            if(item.id==fid){
              item.book[tid].onclick=false;
              return true;
            }
          this.$nextTick(()=>{
            this.reFlash = true
          })
        })
        //改变列表
        let i;
        this.bookList[index].list.some((val,index)=>{
          if(val.fid == fid && val.tid == tid){
            i = index;
            return true;
          }
        })
        this.bookList[index].list.splice(i,1);
        if(this.bookList[index].list.length==0){
          delete this.bookList[index];
        }
        this.countCost -= cost;
        this.$forceUpdate();
      },
      //已预约不可点击
      hasBook(fid,tid){
        let flag = false;
        let dd =new Date(this.canBookDate[this.bookDate].dateTime);
        let y = dd.getFullYear();
        let m = dd.getMonth()+1;
        let d = dd.getDate();
        if(m<10){
          m = '0'+m
        }
        if(d<10){
          d = '0'+d
        }
        let cdate = y+'-'+m+'-'+d;
        this.booklist.some(item=>{
          if(item.tid==tid&&item.sdate==cdate){
            flag = true;
            return true;
          }
        })
        return flag;
      },
      //今天过时不可预约
      obsolete(val,fieldItem,tid){
        if(this.bookDate==0 ){
          let myDate = new Date();
          let nowhour =  myDate.getHours();
          let nowmin = myDate.getMinutes();
          let t = val.split("~")[1].split(":");
          let t1 = parseInt(t[0]);
          let t2 = parseInt(t[1]);
          if(
            t1>nowhour||t1==nowhour&&t2>=nowmin ||
            fieldItem.times.indexOf(tid)==-1 ||
            fieldItem.book[tid].leftseat==0 ||
            this.showAllFieldList[0].book[tid].leftseat<this.showAllFieldList[0].seat&&fieldItem.pid!=0
          ){
            return false;
          }else{
            return true;
          }
        }
        return false;
      },
      //当子场馆被预定，父场馆不点击，且“满”不变色可点击
      canClickDanger(p,tid){
        let res = false;
        if(p.pid==0){
          this.showAllFieldList.forEach(item=>{
            item.book.some(list=>{
              //子场馆是否被预约，父场馆是否满足点击条件
              if(list.tid==tid&&list.leftseat<item.seat&&item.pid!=0){
                //禁止
                res = true;
                return res;
              }
            })
          })
        }
        return res;
      },
      //是否展示右侧列表信息
      showBookList(list){
        let flag = false;
        if(list.length>0){
          list.forEach(item=>{
            if(item.list!=0||item.list!=undefined){
              flag = true;
            }
          })
        }
        return flag;
      },
      //每个预约子项显示内容
      showBookItem(tag){
        let name;
        this.showAllFieldList.some(item=>{
          if(item.id==tag.fid){
            name = item.name;
            return true;
          }
        })
        let time;
        this.parentTimeList.some(t=>{
          if(t.id==tag.tid){
            time = t.time;
            return true;
          }
        })
        return name+' '+time;
      },
      //获取预约备注到暂存区
      showRemark(val){
        this.bookRemark = val;
      },
      //保存备注内容
      saveRemark(n,val){
        this.$set(n,'remark',val);
        this.bookRemark = "";
        //重新渲染 添加/修改备注
        this.$forceUpdate();
      },
      //选择完场次后点击确认预约
      async confirmBook(){
        let list = [];
        this.bookList.forEach(bigList=>{
          bigList.list.forEach(smallList=>{
            this.parentTimeList.some(t=>{
              if(t.id==smallList.tid){
                let a = t.time.split("~")
                smallList.bookStartDate = bigList.dateTime+" "+a[0];
                smallList.bookEndDate = bigList.dateTime+" "+a[1];
                return true;
              }
            })
            smallList.uid = this.$store.getters.userId;
            list.push(smallList);
          })
        })
        let res = await addBookFieldApi(list).catch(res=>{console.log(res)})
        if(res&&res.code==200){
          if(res.data.length==list.length){
            this.ordersAlertType='success'
          }else{
            this.ordersAlertType='warning'
          }
          this.getUserAsset();
          this.ordersAlertTitle = res.msg;
          this.ordersTableData = res.data;
          this.ordersTableData.forEach(item=>{
            this.ordersBookIds.push(item.id);
          })
          this.ordersDialog.visible = true;
          this.comOrderTimeOut = setTimeout(()=>{
            this.autoOnOrdersClose();
          },1000*60)
        }
      },
      //若用户超1分钟停留在确认页面自动关闭
      async autoOnOrdersClose(){
        if(this.ordersDialog.visible){
          let res = await deleteFieldBookApi({ids:this.ordersBookIds});
          if(res&&res.code==200){
            this.ordersDialog.visible = false;
            this.$message.info("确认超时自动取消建立订单");
            clearTimeout(this.comOrderTimeOut);
            this.reFlashRouter();
          }
        }
      },
      //获取用户资产信息
      async getUserAsset(){
        let res = await getAssetByUid({uid:this.$store.getters.userId});
        if(res&&res.code==200){
          this.assetId = res.data.id
          this.allPoint = res.data.point;
          this.balance = res.data.balance;
          if(this.allPoint/1000>this.allCost){
            this.canUsePoint = this.allCost*1000;
          }else{
            this.canUsePoint = this.allPoint;
          }
        }
      },
      //在订单表格中渲染场馆名
      showFieldName(fid){
        let name;
        this.showAllFieldList.some(item=>{
          if(item.id==fid){
            name = item.name;
            return true;
          }
        })
        return name;
      },
      //在订单表格中渲染预约时间
      showBookDateTime(tid,val){
        let time;
        this.parentTimeList.some(t=>{
          if(t.id==tid){
            time = t.time;
            return true;
          }
        })
        let date = val.split(" ")[0];
        return date+" "+time;
      },
      //计算订单总价
      getSummaries({ columns, data }){
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          if (index === columns.length - 1) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every((value,i) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return  prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              let allCost = sums[index];
              if(this.point!=null&&this.point>0){
                this.allCost = (allCost - this.point/1000);
              }else{
                this.allCost = allCost
              }
              if(this.allCost>0){
                sums[index] = this.allCost.toFixed(2)+' 元';
              }else{
                sums[index] = '免费'
              }
            }
          }
        });
        return sums;
      },
      //刷新页面
      reFlashRouter(){
        let fullPath = this.$router.history.current.fullPath;
        this.$router.replace({ path: '/redirect' + fullPath })
      },
      //取消预约
      async onOrdersClose(){
        let confirm = await this.$myconfirm("确定取消此订单建立吗？");
        if (confirm) {
          if(this.ordersBookIds.length>0){
            let res = await deleteFieldBookApi({ids:this.ordersBookIds});
            if(res&&res.code==200){
              this.ordersDialog.visible = false;
              this.$message.info(res.msg);
              clearTimeout(this.comOrderTimeOut);
              this.reFlashRouter();
            }
          }
        }
      },
      //创建订单
      async onOrdersConfirm(){
        clearTimeout(this.comOrderTimeOut);
        let parm = {
          uid: this.$store.getters.userId,
          cost: this.allCost,
          point: this.point,
          type: 0,
          iid: this.ordersBookIds,
        }
        let res = await addNewOrdersApi(parm);
        if(res&&res.code==200){
          this.newOrders = res.data;
          this.ordersDialog.visible = false;
          if(this.allCost==0&&this.point==0){
            this.finishPay();
          }else{
            this.openPayDialog();
          }
        }
      },
      //打开支付弹框
      openPayDialog(){
        this.$refs.payDialogRef.canConfirm = true;
        this.payDialog.visible = true;
        this.payTimeOut = setTimeout(()=>{
          this.autoPayClose();
        },1000*60*10)
        this.ordersStopCountDown = Date.now() + 10 * 1000 * 60;
      },
      //密码框值
      getPayInputValue(value){
        this.payInput = value;
      },
      //获取四则运算验证码
      async getMathCodeImage(){
        this.codeImage = await getMathCodeImageApi();
      },
      //自动关闭支付弹框
      autoPayClose(){
        if(this.payDialog.visible){
          this.payDialog.visible = false;
          this.$message.info("支付超时已自动取消订单");
          this.reFlashRouter();
        }
      },
      //关闭支付弹框
      async onPayClose(){
        let confirm = await this.$myconfirm("关闭后仍可以在订单中心支付");
        if(confirm){
          clearTimeout(this.payTimeOut);
          this.payDialog.visible = false;
          this.reFlashRouter();
        }
      },
      //提交支付信息
      onPayConfirm(){
        if(this.payCount<3){
          this.checkAssetPayKey();
        }else{
          this.checkMathCode();
        }
        if(this.payCount==2){
          this.getMathCodeImage();
        }
      },
      //发起校验密码
      async checkAssetPayKey(){
        let res = await checkAssetKeyApi({id:this.assetId,assetKey:this.payInput}).catch(()=>{
          this.$refs.payInputRef.cleanInput();
          this.payCode='';
          this.payCount++
        });
        if(res&&res.code==200){
          clearTimeout(this.payTimeOut);
          this.finishPay();
          this.payDialog.visible = false;
        }
      },
      //输错三次密码，验证码
      async checkMathCode(){
        let res = await checkMathCodeApi({mathCode:this.payCode}).catch(()=>{
          this.payCode='';
        }).finally(this.getMathCodeImage())
        if(res&&res.code==200){
          this.checkAssetPayKey();
        }
      },
      //完成支付
      async finishPay(){
        let res = await finishPayApi(this.newOrders);
        if(res&&res.code==200){
          this.$message.success(res.msg)
          this.reFlashRouter();
        }

      }
    },
    watch:{
      payInput(val){
        if(val.length>=6){
          this.$refs.payDialogRef.canConfirm = false;
        }else{
          this.$refs.payDialogRef.canConfirm = true;
        }
      }
    },
    filters:{
      showCost(val){
        if(val==0) {
          return '免费'
        }else{
          return val+' 元'
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .bg{
    height: 350px;
    overflow: hidden;
    &::before{
      background-image:linear-gradient(#0e4a85,#155594,#1d649e);
      height: 300px;
      width: 100%;
      position:absolute;
      top:50px;
      z-index: -1
    }
    .fieldPic{
      height: 300px;
      background-repeat:no-repeat;
      background-position:center;
      background-size:cover;
      border-radius: 6px;
    }
    .fieldRemark{
      margin-top:50px;
      padding: 20px 30px 20px 50px;
      font-size: 16px;
      color:#eee;
      overflow: hidden;

      .fieldTitle{
        color:#fff;
        font-size: 36px;
        font-weight: bold;
        padding-left:0.7em;
      }
      .el-row{
      margin-bottom: 10px;
      i + span{
        color:#fff;
      }
      i{
        margin-right: 10px;
      }
      .remark{
        margin-top: 0.2em;
        padding-left: 1.7em;
        color: #fff;
        line-height: 22px;
        overflow: hidden;
        .show{
          width: 24px;
          color: #c2c1c1;
          font-size: 12px;
          position: absolute;
          bottom: -20px;
          right: 8px;
          cursor: pointer;
        }
        .show:hover{
          color:#f3f3f3;
          text-decoration: underline;
        }
      }

    }
    }
  }
  .bookItem{
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 4px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    padding: 0px 20px;
    margin: 5px 10px;
    transition: 0.3s;

    ::v-deep .el-popover__title{
      font-size: 12px;
    }

    .bookText{
      display: initial;
      transition: 0.3s;
    }

    b{
      color:red;
    }

    i{
      display: none;
      margin: 0 3px;
      cursor: pointer;
      transition: 0.3s;
      &:hover{
        color: #409EFF;
      }
    }

    &:hover{
      border: 1px solid #409EFF;
      padding: 0px 20px;
      transition: 0.3s;
    }
    &:hover .bookText{
      display: none;
      transition: 0.3s;
    }

    &:hover i{
      display: initial;
      transition: 0.3s;
    }
  }

  .countCost{
    color: red;
    font-weight: bolder;
    font-size:26px;
  }

  .tiptext{
    margin-bottom: 20px;
    font-size: 14px;
    color: #606266;
  }

  .codeImg {
    width: 100%;
    height: 36px;
    padding: 5px 0;
    border: 1px solid #ddd;
  }
</style>
